package org.clevernote.foundations;

import com.evernote.edam.error.EDAMSystemException;
import com.evernote.edam.error.EDAMUserException;
import com.evernote.edam.type.User;
import com.evernote.edam.userstore.AuthenticationResult;
import com.evernote.edam.userstore.UserStore;
import com.facebook.thrift.TException;
import com.facebook.thrift.protocol.TBinaryProtocol;
import com.facebook.thrift.transport.THttpClient;

public class Authentication {

	private String authToken_;
	private String noteStoreUrl_;

	private boolean doAuthenticate(String username, String password)
			throws TException, EDAMUserException, EDAMSystemException {

		// Set up the UserStore and check that we can talk to the server
		THttpClient userStoreTrans = new THttpClient(
				ClevernoteConstants.USER_STORE_URL);
		TBinaryProtocol userStoreProt = new TBinaryProtocol(userStoreTrans);
		UserStore.Client userStore = new UserStore.Client(userStoreProt,
				userStoreProt);
		boolean versionOk = userStore.checkVersion("Dave's EDAMDemo (Java)",
				com.evernote.edam.userstore.Constants.EDAM_VERSION_MAJOR,
				com.evernote.edam.userstore.Constants.EDAM_VERSION_MINOR);
		if (!versionOk) {
			System.err.println("Incomatible EDAM client protocol version");
			return false;
		}
		// Authenticate as a user & password
		AuthenticationResult authResult = userStore.authenticate(username,
				password, ClevernoteConstants.CONSUMER_KEY,
				ClevernoteConstants.CONSUMER_SECRET);

		User user = authResult.getUser();

		authToken_ = authResult.getAuthenticationToken();
		noteStoreUrl_ = ClevernoteConstants.NOTE_STORE_URL_BASE
				+ user.getShardId();

		return true;
	}

	public void store() {
		Preferences.store(ClevernoteConstants.KEY_AUTH_TOKEN, authToken_);
		Preferences
				.store(ClevernoteConstants.KEY_NOTE_STORE_URL, noteStoreUrl_);
	}

	public void retreive() {
		authToken_ = Preferences.retreive(ClevernoteConstants.KEY_AUTH_TOKEN);
		noteStoreUrl_ = Preferences
				.retreive(ClevernoteConstants.KEY_NOTE_STORE_URL);
	}

	public String getAuthenticationToken() {
		return authToken_;
	}

	public String getNoteStoreUrl() {
		return noteStoreUrl_;
	}

	public static Authentication authenticate(String _username, String _password) throws TException, EDAMUserException,
			EDAMSystemException {
		Authentication auth_ = new Authentication();
	
		boolean authenticated = false;
	
		if (_username != null && _password != null)
			authenticated = auth_.doAuthenticate(_username, _password);
		
		if (!authenticated)
			auth_.retreive();
		
		return auth_ ;
	}
}
